/**
 * 
 */
package org.arpit.masteringextjs.rs;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.masteringextjs.dao.impl.MenuDAOImpl;
import org.arpit.masteringextjs.dao.impl.UserDAOImpl;
import org.arpit.masteringextjs.domain.Menu;
import org.arpit.masteringextjs.domain.User;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @author Arpit.Rathore
 *
 */
@Path("/json/menu")
public class MenuResource {

	@GET
	@Path("/parentMenusByGroupId/{groupId}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Menu> findParentMenusByGroupId(
			@PathParam("groupId") Long groupId) {
		return MenuDAOImpl.getInstance().findParentMenusByGroupId(groupId);
	}

	@GET
	@Path("/findByLoggedInUser")
	@Produces(MediaType.APPLICATION_JSON)
	public String findByUserName(@PathParam("userName") String userName)
			throws JsonGenerationException, JsonMappingException, IOException {

		User user = UserDAOImpl.getInstance().findByUsername("loiane");
		List<Menu> parents = MenuDAOImpl.getInstance()
				.findParentMenusByGroupId(user.getGroups().getId());

		for (Menu menu : parents) {
			menu.setLeaf(false);
			List<Menu> menus = MenuDAOImpl.getInstance().findByParentId(
					menu.getId());
			for (Menu menu2 : menus) {
				menu2.setLeaf(true);
			}
			menu.setItems(menus);
		}

		ObjectMapper mapper = new ObjectMapper();
		String json = "";

		Map<String, Object> map = new HashMap<>();
		map.put("items", parents);

		// convert map to JSON string
		json = mapper.defaultPrettyPrintingWriter().writeValueAsString(map);
		//System.out.println(json);
		return json;

	}
	
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		new MenuResource().findByUserName("");
	}

}
